package com.nisure.tasks;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.nisure.entities.FormCustomerEntity;
import com.nisure.service.FormCustomerService;
import com.nisure.utils.CommonUtils;

@Component
public class FormCustomerTask {
	private Logger logger = LogManager.getLogger(FormCustomerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	//优先同步2天内的数据，并且以公司名作为唯一标识码
	private final Integer queryDay = 1;
	
	@Autowired
	private FormCustomerService formCustomerService;

	
	public void getSynchroNewFormCustomerInfo(String baseDB, String followDB) {
		String dateString = dateFormat.format(new Date());
		logger.info("【从"+baseDB+"到"+followDB+"】"+dateString+"开始同步最新爬虫信息==");
		long starttime = System.currentTimeMillis();
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		Map<String, Object> mapDay = new HashMap<>();
		mapDay.put("queryDay", queryDay);
		List<FormCustomerEntity> list = formCustomerService.selectByParams(mapDay, baseDB);
		if (!list.isEmpty()) {
			int total = list.size();
			int rows = 1000;
			int page = total / rows;
			int res = total % rows;
			if (res != 0) {
				page = page + 1;
			}
			List<List<FormCustomerEntity>> listStr = CommonUtils.averageAssign(list, page);
			List<FormCustomerEntity> insertList = new ArrayList<>(); //需要插入的数据
			List<FormCustomerEntity> updateList = new ArrayList<>(); //需要更新的数据
			for (List<FormCustomerEntity> handleData : listStr) {
				for(FormCustomerEntity formCustomerEntity : handleData){
					String companyName = formCustomerEntity.getCompanyName();
					Map<String, Object> mapCompanyName = new HashMap<>();
					mapCompanyName.put("queryCompanyName", companyName);
					List<FormCustomerEntity> listCompanyName = formCustomerService.selectByParams(mapCompanyName, followDB);
					if(null != listCompanyName && !listCompanyName.isEmpty()){
						updateList.add(formCustomerEntity);
					}else{
						insertList.add(formCustomerEntity);
					}
				}
				
			}
			/*if(!updateList.isEmpty()){
				executorService.submit(new UpdateDataMethod(updateList, followDB));
			}*/
			if(!insertList.isEmpty()){
				logger.info("【从"+baseDB+"到"+followDB+"】"+dateString+"开始同步最新爬虫信息，需要处理新增数据"+insertList.size()+"条");
				executorService.submit(new InsertDataMethod(insertList, followDB));
//				formCustomerService.insertFormCustomers(insertList, followDB);
			}
		}
		executorService.shutdown();
		long endtime = System.currentTimeMillis();
		logger.info("【从"+baseDB+"到"+followDB+"】"+dateString+"同步最新爬虫信息 task finish in "+(endtime-starttime)+" milisecond ==");

	}

	class InsertDataMethod implements Runnable {
		List<FormCustomerEntity> list;
		String dbName;

		public InsertDataMethod(List<FormCustomerEntity> list, String dbName) {
			// TODO Auto-generated constructor stub
			this.list = list;
			this.dbName = dbName;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			formCustomerService.insertFormCustomers(list, dbName);
		}

	}
	
	
	
	public void  getSynchroUpdateFormCustomerInfo(String baseDB, String followDB) {
		String dateString = dateFormat.format(new Date());
		logger.info("【从"+baseDB+"到"+followDB+"】"+dateString+"开始同步更新爬虫信息(优先处理discoverCount>1的公司信息)==");
		long starttime = System.currentTimeMillis();
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		Integer queryDiscoverCount = 1;
		Map<String, Object> mapParams = new HashMap<>();
		mapParams.put("queryDiscoverCount", queryDiscoverCount);
		List<FormCustomerEntity> listParams = formCustomerService.selectByParams(mapParams, followDB);
		if(null != listParams && !listParams.isEmpty()){
			int total = listParams.size();
			int rows = 1000;
			int page = total / rows;
			int res = total % rows;
			if (res != 0) {
				page = page + 1;
			}
			List<List<FormCustomerEntity>> listStr = CommonUtils.averageAssign(listParams, page);
			List<FormCustomerEntity> updateList = new ArrayList<>(); //需要更新的数据
			for (List<FormCustomerEntity> handleData : listStr) {
				for(FormCustomerEntity formCustomerEntity : handleData){
					String companyName = formCustomerEntity.getCompanyName();
					Map<String, Object> mapCompanyName = new HashMap<>();
					mapCompanyName.put("queryCompanyName", companyName);
					List<FormCustomerEntity> listCompanyName = formCustomerService.selectByParams(mapCompanyName, baseDB);
					if(null != listCompanyName && !listCompanyName.isEmpty()){
						FormCustomerEntity fe = listCompanyName.get(0);
						updateList.add(fe);
					}
				}
			}
			if(!updateList.isEmpty()){
				logger.info("【从"+baseDB+"到"+followDB+"】"+dateString+"开始同步更新爬虫信息(优先处理discoverCount>1的公司信息)，需要处理更新数据"+updateList.size()+"条");
				executorService.submit(new UpdateDataMethod(updateList, followDB));
//				for(FormCustomerEntity formCustomerEntity : updateList) {
//					formCustomerService.updateFormCustomer(formCustomerEntity, followDB);
//				}
			}
		}
		executorService.shutdown();
		long endtime = System.currentTimeMillis();
		logger.info("【从"+baseDB+"到"+followDB+"】"+dateString+"同步更新爬虫信息(优先处理discoverCount>1的公司信息) task finish in "+(endtime-starttime)+" milisecond ==");

	}
	
	class UpdateDataMethod implements Runnable {
		List<FormCustomerEntity> list;
		String dbName;
		public UpdateDataMethod(List<FormCustomerEntity> list, String dbName) {
			// TODO Auto-generated constructor stub
			this.list = list;
			this.dbName = dbName;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			for(FormCustomerEntity formCustomerEntity : list) {
				formCustomerService.updateFormCustomer(formCustomerEntity, dbName);
			}
			
		}

	}
	
	@Scheduled(cron = "${jobs.cron.delete}")
	public void deleteFormCustomer() {
//		Map<String, Object> map = new HashMap<>();
//		map.put("deleteId", 1);
//		formCustomerService.deleteFormCustomer(map, "db2");
	}

	/**
	 * 插入新数据没问题了。
	 */
	@Scheduled(cron = "${jobs.cron.insert}")
	public void insertHandleData(){
		getSynchroNewFormCustomerInfo("db1", "db3");
		getSynchroNewFormCustomerInfo("db1", "db2");
	}
	
	/**
	 * 更新数据还有待考察
	 */
	@Scheduled(cron = "${jobs.cron.update}")
	public void updateHandleData(){
		getSynchroUpdateFormCustomerInfo("db1", "db3");
		getSynchroUpdateFormCustomerInfo("db1", "db2");
	}
}
